package com.aimashi.railwaytoolmanagesystem.activity.scantool;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aimashi.commonlib.util.Datetime;
import com.aimashi.commonlib.util.MessageUtil;
import com.aimashi.railwaytoolmanagesystem.R;
import com.aimashi.railwaytoolmanagesystem.bean.Card;
import com.aimashi.railwaytoolmanagesystem.bean.GoodMode;
import com.aimashi.railwaytoolmanagesystem.bean.RecordMode;
import com.aimashi.railwaytoolmanagesystem.bean.ScanCount;
import com.aimashi.railwaytoolmanagesystem.bean.ScanMode;
import com.aimashi.railwaytoolmanagesystem.utils.ComponentUtil;
import com.aimashi.railwaytoolmanagesystem.utils.DatabaseCardUtil;
import com.aimashi.railwaytoolmanagesystem.utils.DatabaseGoodModeUtil;
import com.aimashi.railwaytoolmanagesystem.utils.DatabaseRecordModeUtil;
import com.aimashi.railwaytoolmanagesystem.utils.DatabaseScanCountUtil;
import com.aimashi.railwaytoolmanagesystem.utils.DatabaseScanModeUtil;
import com.aimashi.railwaytoolmanagesystem.utils.ScanToolVoiceUtil;
import com.aimashi.railwaytoolmanagesystem.utils.VoiceQueue;
import com.android.hdhe.uhf.reader.Tools;
import com.android.hdhe.uhf.reader.UhfReader;
import com.lidroid.xutils.util.LogUtils;

/**
 * 银行卡操作的类
 * 
 * @author zhaoys
 * 
 */
public class ScanTool extends Fragment {
	
	public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int RESULT_CANCELED = 0;
    public static final int RESULT_OK = -1;
    public static final int RESULT_FIRST_USER = 1;
    

	private boolean runFlag = true;

	private boolean startFlag = false;

	/**
	 * 未扫描到的数量
	 */
	private int noScanNumber = 0;

	/**
	 * 存放语音播放队列
	 */
	VoiceQueue queue;

	/**
	 * 操作sqlite数据库
	 */
	private DatabaseCardUtil dbmCardManager;

	private DatabaseScanCountUtil scanCountManager;
	
	private DatabaseRecordModeUtil dbmRecordModeUtil;
	
	private DatabaseScanModeUtil dbmScanModeUtil;
	
	private DatabaseGoodModeUtil dbmGoodModeUtil;
	
	

	private View mMainView;

	private UhfReader reader; // 读取工具类
	/**
	 * 开始扫描
	 */
	private Button btnStartScan;
	/**
	 * 结束扫描
	 */
	private Button btnEndScan;

	private TextView titleTextView;

	private TextView countTextView;

	private ListView toolList;

	List<Card> listCard;

	ScanCount scanCount;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		reader = UhfReader.getInstance();
		if (reader == null) {
			MessageUtil.alert(getActivity(), "获取读写器实例失败", Toast.LENGTH_LONG);
		} else {
			MessageUtil.alert(getActivity(), "获取读写器实例成功", Toast.LENGTH_SHORT);
			reader.setOutputPower(26);
		}

		dbmCardManager = new DatabaseCardUtil(getActivity());

		scanCountManager = new DatabaseScanCountUtil(getActivity());
		
		dbmRecordModeUtil = new DatabaseRecordModeUtil(getActivity());
		
		dbmScanModeUtil = new DatabaseScanModeUtil(getActivity());
		
		dbmGoodModeUtil = new DatabaseGoodModeUtil(getActivity());

		List<ScanCount> tempScanCountList = scanCountManager.findAllScanCountByName("");
		String tempNowDay = Datetime.nowDateTime("yyyy-MM-dd");
		if (tempScanCountList == null || tempScanCountList.size() == 0) {
			scanCount = new ScanCount();
			scanCount.setCount(1);
			scanCount.setDate(tempNowDay);
			scanCountManager.add(scanCount);
		} else {
			ScanCount tempObj = tempScanCountList.get(0);
			//如果存储的时间与当前时间不一样将清除之前的记录
			if(tempNowDay.equals(tempObj.getDate()))
				scanCount = tempScanCountList.get(0);
			else{
				scanCount = new ScanCount();
				scanCount.setCount(1);
				scanCount.setDate(tempNowDay);
				scanCountManager.UpdateScanCount(scanCount);
			}
		}

		listCard = dbmCardManager.findAllCardByName("");
		if (listCard == null || listCard.size() == 0) {
			dbmCardManager.initRecord();
			listCard = dbmCardManager.findAllCardByName("");
		}
		queue = new VoiceQueue(listCard.size());
		LogUtils.i("fragment2-->onCreate()");

		LayoutInflater inflater = getActivity().getLayoutInflater();
		mMainView = inflater.inflate(R.layout.scantool,
				(ViewGroup) getActivity().findViewById(R.id.setting_viewPager),
				false);
		toolList = (ListView) mMainView.findViewById(R.id.tool_list);

		titleTextView = (TextView) mMainView.findViewById(R.id.tool_title);
		setCountTitle();
		countTextView = (TextView) mMainView.findViewById(R.id.tool_count);
		countTextView.setText(noScanNumber + "/" + listCard.size());

		btnStartScan = (Button) mMainView.findViewById(R.id.scantool_start);
		btnStartScan.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (listCard == null || listCard.size() == 0) {
					MessageUtil.alert(getActivity(), "没有可用扫描的数据",Toast.LENGTH_SHORT);
					return;
				}
				if(scanCount.getCount() > 6){
					MessageUtil.alert(getActivity(), "已经完成当天扫描任务，请明天再试",Toast.LENGTH_SHORT);
					return;
				}
				if(null != queue)
					queue.deleteAll(listCard.size());
				if(scanCount.isImgFlag()){
					if(scanCount.getCount() == 1){ //针对第一次扫描做判断
						firstScanAlert();
					}else{
						scanStart();
					}
				}else{
					openCamera();
				}
			}
		});

		btnEndScan = (Button) mMainView.findViewById(R.id.scantool_end);
		btnEndScan.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				setScanFlag(false);
				// 播放提示音
				ScanToolVoiceUtil.callAlarmAsEndScan(getActivity());
				saveScanData();
			}
		});

		toolList.setAdapter(new ToolAdapter(getActivity(), listCard));

		setScanFlag(false);
		Thread thread = new InventoryThread();
		thread.start();

		Thread voiceThread = new VoiceThread();
		voiceThread.start();
		
		
		new Handler().postDelayed(new Runnable() {
			public void run() {
				if(!scanCount.isImgFlag()){
					ScanToolVoiceUtil.callAlarmAsCustom(getActivity(), R.raw.ispicture);
					openCamera();
				}
			}
		}, 1000); // 等待2秒进主界面
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		LogUtils.i("fragment2-->onCreateView()");

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
			LogUtils.i("fragment2-->�Ƴ��Ѵ��ڵ�View");
		}
		return mMainView;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		LogUtils.i("fragment2-->onDestroy()");
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		runFlag = false;
		if(null != queue)
			queue.deleteAll(listCard.size());
		LogUtils.i("fragment2-->onPause()");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(!runFlag){
			runFlag = true;
			Thread thread = new InventoryThread();
			thread.start();

			Thread voiceThread = new VoiceThread();
			voiceThread.start();			
		}
		LogUtils.i("fragment2-->onResume()");
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if(!runFlag){
			runFlag = true;
			Thread thread = new InventoryThread();
			thread.start();

			Thread voiceThread = new VoiceThread();
			voiceThread.start();			
		}
		LogUtils.i("fragment2-->onStart()");
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		runFlag = false;
		if(null != queue)
			queue.deleteAll(listCard.size());
		LogUtils.i("fragment2-->onStop()");
	}

	/**
	 * 盘存线程
	 * 
	 * @author Administrator
	 * 
	 */
	class InventoryThread extends Thread {
		private List<byte[]> epcList;

		@Override
		public void run() {
			super.run();
			while (runFlag) {
				if (startFlag) {
					// reader.stopInventoryMulti()
					epcList = reader.inventoryRealTime(); // 实时盘存
					if (epcList != null && !epcList.isEmpty()) {
						for (byte[] epc : epcList) {
							String epcStr = Tools.Bytes2HexString(epc,epc.length);
							mHandler.obtainMessage(0, epcStr).sendToTarget();
						}
					}
					epcList = null;
					try {
						Thread.sleep(40);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

	private Handler mHandler = new Handler() {
		// 重写handleMessage()方法，此方法在UI线程运行
		@Override
		public void handleMessage(Message msg) {
			scanAddToList((String) msg.obj);
		}
	};
	
	boolean flagSuccess = true;
	// 将读取的EPC添加到LISTVIEW
	private void scanAddToList(String epc) {
		boolean flag = true;
		for (Card item : listCard) {
			if (!item.isBack() && flag)
				flag = false;
			if (item.getEpcNumber().equals(epc) && !item.isBack()) {
				item.setBack(true);
				noScanNumber++;
				setListDataFlag(item);
				queue.enqueue(item.getEpcMusic());
			}
		}
		if (flag && flagSuccess) {
			// 播放提示音
			setScanFlag(false);
			saveScanData();
			flagSuccess = false;
		}
	}

	/**
	 * 设置扫描状态
	 * 
	 * @param flag
	 */
	private void setScanFlag(boolean flag) {
		startFlag = flag;
		flagSuccess = flag;
		ComponentUtil.setButtonClickable(btnEndScan, flag);
		btnStartScan.setText(flag ? "重新扫描" : "开始扫描");
	}

	/**
	 * 设置当前标签状态
	 * 
	 * @param pdata
	 */
	private void setListDataFlag(Card pdata) {
		Date tempDate = new Date();
		String tempTime = tempDate.getHours() + ":" + tempDate.getMinutes();// tempDate.getSeconds()
		if (pdata.isBack())
			pdata.setScanTime(tempTime);
		else
			pdata.setScanTime("");
		dbmCardManager.UpdateCard(pdata);
		toolList.setAdapter(new ToolAdapter(getActivity(), listCard));
		countTextView.setText(noScanNumber + "/" + listCard.size());
	}

	/**
	 * 结束扫描
	 */
	private void scanEndVoice() {
		String tempNowDay = Datetime.nowDateTime("yyyy-MM-dd");
		String tempDateTime = Datetime.nowDateTime("HH:mm");
		RecordMode tempRecordMode = dbmRecordModeUtil.findRecordModeByDate(tempNowDay);
		dbmRecordModeUtil.findAllRecordModeByDate("");
		if(null == tempRecordMode){
			RecordMode newObj = new RecordMode();
					   newObj.setRecordDate(tempNowDay);
			dbmRecordModeUtil.add(newObj);
		}
		
	    ScanMode tempScanMode = dbmScanModeUtil.findScanModeByPath(fileUri.getPath());
		if(null == tempScanMode){
			ScanMode newObj = new ScanMode();
					   newObj.setScanCount(scanCount.getCount());
					   newObj.setImgPath(fileUri.getPath());
					   newObj.setEndDate(tempNowDay);
					   newObj.setEndTime(tempDateTime);
					   dbmScanModeUtil.add(newObj);
			GoodMode newGood = null;
			for(Card item:listCard){
				newGood = new GoodMode();
				newGood.setEpcNumberCountEndDate(item.getEpcNumber()+scanCount.getCount()+tempNowDay);
				newGood.setEndDateCount(tempNowDay + scanCount.getCount());
				newGood.setBack(item.isBack());
				newGood.setEpcDesc(item.getEpcDesc());
				newGood.setEpcMusic(item.getEpcMusic());
				newGood.setEpcNumber(item.getEpcNumber());
				newGood.setScanCount(scanCount.getCount());
				newGood.setScanTime(item.getScanTime());
				dbmGoodModeUtil.add(newGood);
			}
		}
		scanCount.setCount(scanCount.getCount()+1);
		scanCount.setImgFlag(false);
		scanCountManager.UpdateScanCount(scanCount);
		setCountTitle();
	}

	/**
	 * 设置Title
	 */
	private void setCountTitle(){
		if(scanCount.getCount() > 6)
			titleTextView.setText("第6扫描");
		else
			titleTextView.setText("第" + scanCount.getCount() + "扫描");
	}
	
	/**
	 * 第一次扫描弹出框
	 */
	private void firstScanAlert(){
		ScanToolVoiceUtil.callAlarmAsCustom(getActivity(), R.raw.isscan);
		new AlertDialog.Builder(getActivity())
				.setTitle("系统提示")
				.setMessage("是否扫描")
				.setPositiveButton("是",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								scanStart();
							}
						}).setNegativeButton("否", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								getActivity().finish();
							}
						}).show();
	}
	
	/**
	 * 保存用户扫描结果
	 */
	private void saveScanData(){
		new AlertDialog.Builder(getActivity())
		.setTitle("系统提示")
		.setMessage("是否保存扫描结果")
		.setPositiveButton("是",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						queue.deleteAll(listCard.size());
						boolean flag = true;
						for (Card item : listCard) {
							if (!item.isBack()) {
								if (flag) {
									ScanToolVoiceUtil.callAlarmAsCustom(getActivity(),R.raw.deficiency);
									try {
										Thread.sleep(1500);// 暂停2.5秒播报下一条
									} catch (InterruptedException e) {
										// TODO Auto-generated
										// catch block
										e.printStackTrace();
									}
								}
								flag = false;
								queue.enqueue(item.getEpcMusic());
							}
						}
						if (flag) {
							ScanToolVoiceUtil.callAlarmAsCustom(getActivity(),R.raw.allscan);
						}
						scanEndVoice();
						btnStartScan.setText("开始扫描");
					}
				}).setNegativeButton("否",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						btnStartScan.setText("重新扫描");
					}
				}).show();
	}
	/**
	 * 开始扫描操作
	 */
	private void scanStart(){
		noScanNumber = 0; //每次扫描将未扫描数变为0
		// 播放提示音
		ScanToolVoiceUtil.callAlarmAsStartScan(getActivity());
		for (Card item : listCard) {
			item.setBack(false);
			setListDataFlag(item);
		}
		setScanFlag(true);
	}
	/******************************** 语音播报升级 ****************************************/
	/**
	 * 盘存线程
	 * 
	 * @author Administrator
	 * 
	 */
	class VoiceThread extends Thread {
		@Override
		public void run() {
			super.run();
			while (runFlag) {
				if (!queue.isEmpty()) {
					voiceHandler.obtainMessage(0, queue.dequeue())
							.sendToTarget();
					try {
						Thread.sleep(2500);// 暂停2.5秒播报下一条
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

	private Handler voiceHandler = new Handler() {
		// 重写handleMessage()方法，此方法在UI线程运行
		@Override
		public void handleMessage(Message msg) {
			ScanToolVoiceUtil.callAlarmAsCustom(getActivity(),
					(int) Integer.valueOf(msg.obj.toString()));
		}
	};
	/******************** 拍照功能 **************************************/
	private static final String LOG_TAG = "RailwayToolManageSystem";
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

	private Uri fileUri;

	private void openCamera() {
		// 摄像
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		// create a file to save the video
		fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
		// set the image file name
		intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

		startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(LOG_TAG, "onActivityResult: requestCode: " + requestCode
				+ ", resultCode: " + requestCode + ", data: " + data);
		// 如果是拍照
		if (CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE == requestCode) {
			Log.d(LOG_TAG, "CAPTURE_IMAGE");

			if (RESULT_OK == resultCode) {
				Log.d(LOG_TAG, "RESULT_OK");
				scanCount.setImgFlag(true);
			} else if (resultCode == RESULT_CANCELED) {
				// User cancelled the image capture
			} else {
				// Image capture failed, advise user
			}
		}
	}

	/** Create a file Uri for saving an image or video */
	private static Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(int type) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		File mediaStorageDir = null;
		try {
			// This location works best if you want the created images to be
			// shared
			// between applications and persist after your app has been
			// uninstalled.
			mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
					"RailwayToolManageSystem");

			Log.d(LOG_TAG, "Successfully created mediaStorageDir: "
					+ mediaStorageDir);

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(LOG_TAG, "Error in Creating mediaStorageDir: "
					+ mediaStorageDir);
		}

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				// 在SD卡上创建文件夹需要权限：
				// <uses-permission
				// android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
				Log.d(LOG_TAG,
						"failed to create directory, check if you have the WRITE_EXTERNAL_STORAGE permission");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			String tempPath = mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".jpg";
			mediaFile = new File(tempPath);
		}  else {
			return null;
		}

		return mediaFile;
	}

}
